package com.ruoyi.basebill.task;

import com.ruoyi.basebill.domain.*;
import com.ruoyi.basebill.service.IOmsDeliverbillService;
import com.ruoyi.basebill.service.IOmsStocktransferbillService;
import com.ruoyi.basebill.service.IOmsTransferbillService;
import com.ruoyi.basebill.service.impl.OmsPurinwarehsbillServiceImpl;
import com.ruoyi.basebill.service.impl.OmsSaleissuebillServiceImpl;
import com.ruoyi.basebill.task.util.OmsTaskUtil;
import com.ruoyi.basedata.domain.*;
import com.ruoyi.basedata.mapper.OmsOrgunitMapper;
import com.ruoyi.basedata.service.IBdWarehouseService;
import com.ruoyi.basedata.service.impl.BdCustomerServiceImpl;
import com.ruoyi.basedata.service.impl.BdMaterialServiceImpl;
import com.ruoyi.basedata.service.impl.BdSupplierServiceImpl;
import com.ruoyi.basedata.service.impl.OmsOrgunitServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 定时读取调拨单，生成下游单据
 */
@Component("OmsTransferbillTask")
public class OmsTransferbillTask {

    @Autowired
    private OmsSaleissuebillServiceImpl saleissuebillService;

    @Autowired
    private OmsPurinwarehsbillServiceImpl purinwarehsbillService;

    @Autowired
    private BdSupplierServiceImpl supplierService;

    @Autowired
    private BdCustomerServiceImpl customerService;

    @Autowired
    private BdMaterialServiceImpl materialService;

    @Autowired
    private IBdWarehouseService bdWarehouseService;

    @Autowired
    private IOmsStocktransferbillService omsStocktransferbillService;

    @Autowired
    private IOmsTransferbillService omsTransferbillService;

    @Autowired
    private OmsTaskUtil omsTaskUtil;

    @Autowired
    private OmsOrgunitServiceImpl orgunitService;

    @Autowired
    private OmsOrgunitMapper omsOrgunitMapper;

    @Autowired
    private OmsTransferbillTask omsTransferbillTask;

    /**
     * 调拨单逻辑
     * 1、调出组织==调入组织-->库存调拨单
     * 2、调入组织!=调出组织
     *      2.1、一级组织同时为分子公司,生成一组调出调入组织和实业1.10.100的中转单
     *      2.2、不同时为分子公司，直接生成调出调入之间的销出采入
     * 3、生成调出组织到调出一级组织之间的销出采入
     * 4、生成调入组织到调入一级组织之间的销入采出
     */
    public void pushDown() {
        for (OmsTransferbill omsTranbill : selectPushDown()) {
            omsTranbill = omsTransferbillService.selectOmsTransferbillById(omsTranbill.getId());
            OmsTransferbill omsTransferbill1 = omsTransferbillTask.pushDownMethod(omsTranbill);
            omsTransferbillService.updateOmsTransferbill(omsTransferbill1);
        }

    }

    private List<OmsTransferbill> selectPushDown() {
        OmsTransferbill omsTransferbill = new OmsTransferbill();
        omsTransferbill.setIscreatebill(0L);
        List<OmsTransferbill> omsTransferbills = omsTransferbillService.selectOmsTransferbillList(omsTransferbill);
        omsTransferbill.setIscreatebill(-1L);
        List<OmsTransferbill> omsTransferbills1 = omsTransferbillService.selectOmsTransferbillList(omsTransferbill);
        if (omsTransferbills1 != null && omsTransferbills1.size() != 0) {
            omsTransferbills.addAll(omsTransferbills1);
        }
        return omsTransferbills;
    }

    @Transactional
    public OmsTransferbill pushDownMethod(OmsTransferbill omsTranbill) {
        String ordertype = omsTranbill.getOrdertype();
        String base_return = "BASE_RETURN";
        String tranIncode = omsTranbill.getInventoryorganizationentercode();
        String tranOutcode = omsTranbill.getInventoryorganizationoutcode();
        if (StringUtils.isBlank(tranIncode) || StringUtils.isBlank(tranOutcode)) {
            omsTranbill.setReason("调出仓库或调入仓库为空");
            omsTranbill.setIscreatebill(-1L);
            return omsTranbill;
        }
        //调出组织编码=调入组织编码
        try {
            //如果调出组织编码=调入组织编码，则生成一张库存调拨单，生成成功后直接结束
            if (!StringUtils.isBlank(tranIncode) && tranIncode.equals(tranOutcode)) {
                OmsStocktransferbill omsStocktransferbill = new OmsStocktransferbill();
                omsStocktransferbill.setBizdate(omsTranbill.getReceiptdate());
                omsStocktransferbill.setBillnumber(omsTaskUtil.setBillNumber(omsStocktransferbill));
                omsStocktransferbill.setBiztypenumber("331");
                omsStocktransferbill.setBiztypename("跨仓库调拨（成本价）");
                omsStocktransferbill.setIssuestorageorgnumber(omsTranbill.getInventoryorganizationoutcode());
                omsStocktransferbill.setIssuestorageorgname(omsTranbill.getInventoryorganizationoutname());
                omsStocktransferbill.setReceiptstorageorgnumber(omsTranbill.getInventoryorganizationentercode());
                omsStocktransferbill.setReceiptstorageorgname(omsTranbill.getInventoryorganizationentername());
                omsStocktransferbill.setOutcostcenternumber(omsTranbill.getCostcenteroutcode());
                omsStocktransferbill.setOutcostcentername(omsTranbill.getCostcenteroutname());
                omsStocktransferbill.setOutaccountcompanynumber(omsTranbill.getInventoryorganizationoutcode());
                omsStocktransferbill.setOutaccountcompanyname(omsTranbill.getInventoryorganizationoutname());
                omsStocktransferbill.setIncostcenternumber(omsTranbill.getCostcenterentercode());
                omsStocktransferbill.setIncostcentername(omsTranbill.getCostcenterentername());
                omsStocktransferbill.setInaccountcompanynumber(omsTranbill.getInventoryorganizationentercode());
                omsStocktransferbill.setInaccountcompanyname(omsTranbill.getInventoryorganizationentername());
                omsStocktransferbill.setSrcbilltype("调拨单");
                omsStocktransferbill.setCurrency("CNY");
                omsStocktransferbill.setExchangerate(new BigDecimal(1));
                omsStocktransferbill.setSrcbilltype("调拨单");
                omsStocktransferbill.setSrcbillnumber(omsTranbill.getCode());
                omsStocktransferbill.setCreatetime(new Date());
                omsStocktransferbill.setSrcsys(omsTranbill.getsrcsys());
                List<OmsStocktransferbillentry> omsStocktransferbillentry = new ArrayList();
                if (omsTranbill.getOmsTransferbillentryList() != null) {
                    for (OmsTransferbillentry tranbillentry : omsTranbill.getOmsTransferbillentryList()) {
                        OmsStocktransferbillentry stocktransferbillentry = new OmsStocktransferbillentry();
                        stocktransferbillentry.setMaterialnumber(tranbillentry.getSkucode());
                        stocktransferbillentry.setMaterialname(tranbillentry.getSkuname());
                        stocktransferbillentry.setIssuewarehousenumber(omsTranbill.getFacilitycode());
                        stocktransferbillentry.setIssuewarehousename(omsTranbill.getFacilityname());
                        stocktransferbillentry.setReceiptwarehousenumber(omsTranbill.getTofacilitycode());
                        stocktransferbillentry.setReceiptwarehousename(omsTranbill.getTofacilityname());
                        stocktransferbillentry.setUnitnumber(tranbillentry.getUnit());
                        stocktransferbillentry.setBaseunitnumber(tranbillentry.getBaseunit());
                        stocktransferbillentry.setQty(tranbillentry.getShipqty());
                        stocktransferbillentry.setIspresent(0L);
                        stocktransferbillentry.setBaseqty(tranbillentry.getBaseshipqty());
                        //修改库存调拨单分录的计划调出和计划调入日期获取来源
                        stocktransferbillentry.setIssueplandate(omsTranbill.getTradecreatedat());
                        stocktransferbillentry.setReceiptplandate(omsTranbill.getTradecreatedat());
//                        stocktransferbillentry.setIssueplandate(omsTranbill.getDeliverydate());
//                        stocktransferbillentry.setReceiptplandate(omsTranbill.getTradecreatedat());
                        omsStocktransferbillentry.add(stocktransferbillentry);
                    }
                }
                omsStocktransferbill.setOmsStocktransferbillentryList(omsStocktransferbillentry);
                omsStocktransferbillService.insertOmsStocktransferbill(omsStocktransferbill);
                omsTranbill.setIscreatebill(1L);
                omsTranbill.setReason("");
                return omsTranbill;
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            omsTranbill.setReason("调出组织编码=调入组织编码,生成库存调拨单时报错");
            omsTranbill.setIscreatebill(-1L);
            return omsTranbill;
        }
        //调出组织编码!=调入组织编码
        try {
            //调出组织编码!=调入组织编码
            if (!StringUtils.isBlank(tranIncode) && !tranIncode.equals(tranOutcode)) {
                OmsOrgunit TranInFirstOrg = omsTaskUtil.getFirstOrg(tranIncode);
                OmsOrgunit TranOutFirstOrg = omsTaskUtil.getFirstOrg(tranOutcode);
                if (StringUtils.isNull(TranInFirstOrg) || StringUtils.isNull(TranOutFirstOrg)){
                    throw new RuntimeException("调出或调入组织的一级组织为空");
                }
                //如果调出和调入的一级组织不相同
                OmsOrgunit orgNode = TranOutFirstOrg;//销退一级组织
                OmsOrgunit omsOrgunitIn = new OmsOrgunit();
                omsOrgunitIn.setOrgnumber(tranIncode);
                OmsOrgunit omsOrgunitOut = new OmsOrgunit();
                omsOrgunitOut.setOrgnumber(tranOutcode);
                List<OmsOrgunit> omsOrgunits1 = orgunitService.selectOmsOrgunitList(omsOrgunitIn);
                List<OmsOrgunit> omsOrgunits2 = orgunitService.selectOmsOrgunitList(omsOrgunitOut);
                if (StringUtils.isEmpty(omsOrgunits2)) {
                    omsTranbill.setReason("调出组织:" + tranOutcode + "不存在");
                    omsTranbill.setIscreatebill(-1L);
                    return omsTranbill;
                } else if (StringUtils.isEmpty(omsOrgunits1)) {
                    omsTranbill.setReason("调入组织:" + tranIncode + "不存在");
                    omsTranbill.setIscreatebill(-1L);
                    return omsTranbill;
                }
                omsOrgunitIn = omsOrgunits1.get(0);
                omsOrgunitOut = omsOrgunits2.get(0);
                //一级组织相同，找出最近节点(调入一级组织--调出一级组织)
                if (TranInFirstOrg.getOrgnumber().equals(TranOutFirstOrg.getOrgnumber())) {
                    orgNode = omsTaskUtil.getOrgNode(omsOrgunitIn, omsOrgunitOut);
                }
                else if (TranInFirstOrg.getIssub().equals(1L) && TranOutFirstOrg.getIssub().equals(1L)) {
                    //调出调入一级组织，同时为分子公司
                    //调出组织一级组织卖给实业1.10.100生成的单据
                    OmsOrgunit omsOrgunit = new OmsOrgunit();
                    omsOrgunit.setOrgnumber("1.10.100");
                    List<OmsOrgunit> omsOrgunits = orgunitService.selectOmsOrgunitList(omsOrgunit);
                    Map map = null;
                    if(base_return.equals(ordertype)){
                        map = tranOutCreatSal(TranOutFirstOrg, omsTranbill
                                ,omsOrgunits.get(0) , omsOrgunitIn, true,new BigDecimal("1"),true);
                    }else{
                        map = tranOutCreatSal(omsOrgunits.get(0), omsTranbill
                                , TranOutFirstOrg, omsOrgunitIn, true,new BigDecimal("-1"),false);
                    }
                    if (map.containsKey("reason")) {
                        throw new Exception(map.get("reason").toString());
                    }
                    OmsSaleissuebill omsSaleissuebill = (OmsSaleissuebill) map.get("target");
                    saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
                    Map map1 = null;
                    if(base_return.equals(ordertype)){
                        map1 = tranOutCreatPur(omsOrgunits.get(0), omsTranbill, omsSaleissuebill
                                , TranOutFirstOrg, omsOrgunitOut, true,true);
                    }else{
                        map1 = tranOutCreatPur(TranOutFirstOrg, omsTranbill, omsSaleissuebill
                                , omsOrgunits.get(0), omsOrgunitOut, true,false);
                    }
                    if (map1.containsKey("reason")) {
                        throw new Exception(map1.get("reason").toString());
                    }
                    OmsPurinwarehsbill omsPurinwarehsbill = (OmsPurinwarehsbill) map1.get("target");
                    purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
                    //生成一组实业1.10.100卖给调入一级组织的单据
                    Map map2 = null;
                    if(base_return.equals(ordertype)){
                        map2 = tranInCreatSal(TranInFirstOrg, omsTranbill, omsOrgunits.get(0)
                                , omsOrgunitOut, true,new BigDecimal("-1"),true);
                    }else{
                        map2 = tranInCreatSal(omsOrgunits.get(0), omsTranbill, TranInFirstOrg
                                , omsOrgunitOut, true,new BigDecimal("1"),false);
                    }
                    if (map2.containsKey("reason")) {
                        throw new Exception(map2.get("reason").toString());
                    }
                    OmsSaleissuebill omsSaleissuebill1 = (OmsSaleissuebill) map2.get("target");
                    saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill1);
                    Map map3 = null;
                    if(base_return.equals(ordertype)){
                        map3 = tranInCreatPur(omsOrgunits.get(0), omsTranbill, omsSaleissuebill1
                                , TranInFirstOrg, omsOrgunitIn, true,true);
                    }else{
                        map3 = tranInCreatPur(TranInFirstOrg, omsTranbill, omsSaleissuebill1
                                , omsOrgunits.get(0), omsOrgunitIn, true,false);
                    }
                    if (map3.containsKey("reason")) {
                        throw new Exception(map3.get("reason").toString());
                    }
                    OmsPurinwarehsbill omsPurinwarehsbill1 = (OmsPurinwarehsbill) map3.get("target");
                    purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill1);
                }
                else {
                    //调出调入一级组织，不同时为分子公司
                    //调出组织一级组织生成的销售出库单
                    Map map = null;
                    if(base_return.equals(ordertype)){
                        map = FirstOrgTranSal(TranInFirstOrg, TranOutFirstOrg, omsTranbill, omsOrgunitOut,new BigDecimal("-1"),true);
                    }else{
                        map = FirstOrgTranSal(TranOutFirstOrg, TranInFirstOrg, omsTranbill, omsOrgunitOut,new BigDecimal("1"),false);
                    }
                    if (map.containsKey("reason")) {
                        omsTranbill.setReason(map.get("reason").toString());
                        omsTranbill.setIscreatebill(-1L);
                        return omsTranbill;
                    }
                    OmsSaleissuebill omsSaleissuebill = (OmsSaleissuebill) map.get("target");
                    saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
                    //调出组织一级组织生成的采购入库单
                    Map map1 = null;
                    if(base_return.equals(ordertype)){
                        map1 = FirstOrgTranPur(TranInFirstOrg, TranOutFirstOrg, omsSaleissuebill, omsOrgunitIn, omsTranbill,true);
                    }else{
                        map1 = FirstOrgTranPur(TranOutFirstOrg, TranInFirstOrg, omsSaleissuebill, omsOrgunitIn, omsTranbill,false);
                    }
                    if (map1.containsKey("reason")) {
                        omsTranbill.setReason(map1.get("reason").toString());
                        omsTranbill.setIscreatebill(-1L);
                        return omsTranbill;
                    }
                    OmsPurinwarehsbill omsPurinwarehsbill = (OmsPurinwarehsbill) map1.get("target");
                    purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
                }
                //调出组织到节点之间所有的销出采入
                Map tranOutMap = tranOutrecurPush(orgNode, omsTranbill, omsOrgunitIn, omsOrgunitOut);
                if (tranOutMap.containsKey("reason")) {
                    omsTranbill.setReason("" + tranOutMap.get("reason"));
                    omsTranbill.setIscreatebill(-1L);
                    throw new Exception(tranOutMap.get("reason").toString());
                }
                if (orgNode.equals(TranOutFirstOrg)) {
                    orgNode = TranInFirstOrg;//销售一级组织
                }
                //调入组织到节点之间所有的销出采入
                Map tranInMap = tranInrecurPush(orgNode, omsTranbill, omsOrgunitIn, omsOrgunitOut);
                if (tranInMap.containsKey("reason")) {
                    omsTranbill.setReason("" + tranInMap.get("reason"));
                    omsTranbill.setIscreatebill(-1L);
                    throw new Exception(tranInMap.get("reason").toString());
                }
                omsTranbill.setIscreatebill(1L);
                omsTranbill.setReason("");
                return omsTranbill;
            }
        } catch (Exception e) {

            String ret = "";

            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            String s = e.toString();
            String[] split = s.split("java.lang.Exception:");
            StringBuffer stringBuffer = new StringBuffer();
            if (split.length != 0) {
                stringBuffer.append(split[split.length - 1]);
                stringBuffer.append("\n"+ret);
                omsTranbill.setReason(stringBuffer.toString());
                omsTranbill.setIscreatebill(-1L);
                return omsTranbill;
            }
            stringBuffer.append(e);
            stringBuffer.append("\n"+ret);
            omsTranbill.setReason(stringBuffer.toString());
            omsTranbill.setIscreatebill(-1L);
            return omsTranbill;
        }
        return omsTranbill;
    }

    /**
     * 顶级节点不同--销售出
     *
     * @param salOrg     销售组织
     * @param purOrg     采购组织
     * @param omsTran    调拨单
     * @param tranOutOrg 调出组织
     * @return Map
     */
    private Map FirstOrgTranSal(OmsOrgunit salOrg, OmsOrgunit purOrg
            , OmsTransferbill omsTran, OmsOrgunit tranOutOrg,BigDecimal qty,boolean isReturn) {
        Map map = new HashMap();
        try {
            OmsSaleissuebill omsSaleissuebill = new OmsSaleissuebill();
            omsSaleissuebill.setBizdate(omsTran.getReceiptdate());
            omsSaleissuebill.setBillnumber(omsTaskUtil.setBillNumber(omsSaleissuebill));
            omsSaleissuebill.setStorageorgnumber(salOrg.getOrgnumber());
            omsSaleissuebill.setStorageorgname(salOrg.getOrgname());
            if(isReturn){
                omsSaleissuebill.setBiztypenumber("211");
                omsSaleissuebill.setBiztypename("普通销售退货");
                omsSaleissuebill.setTransactiontypenumber("013");
                omsSaleissuebill.setTransactiontypename("成本出库退货");
            }else{
                omsSaleissuebill.setBiztypenumber("210");
                omsSaleissuebill.setBiztypename("普通销售");
                omsSaleissuebill.setTransactiontypenumber("012");
                omsSaleissuebill.setTransactiontypename("成本出库");
            }
            BdCustomer bdCustomer = new BdCustomer();
            bdCustomer.setInternalcompanynumber(purOrg.getOrgnumber());
            List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
            bdCustomer = bdCustomers.get(0);
            omsSaleissuebill.setCustomernumber(bdCustomer.getCustomernumber());
            omsSaleissuebill.setCustomername(bdCustomer.getCustomername());
            omsSaleissuebill.setAccountcompanynumber(salOrg.getOrgnumber());
            omsSaleissuebill.setAccountcompanyname(salOrg.getOrgname());
            omsSaleissuebill.setCostcenternumber("1.91");
            omsSaleissuebill.setCostcentername("关联单位");
            omsSaleissuebill.setCurrency("CNY");
            omsSaleissuebill.setExchangerate(new BigDecimal(1));
            omsSaleissuebill.setSrcbilltype("调拨单");
            omsSaleissuebill.setSrcbillnumber(omsTran.getCode());
            omsSaleissuebill.setCreatetime(new Date());
            omsSaleissuebill.setIsoutcustomer(0L);
            omsSaleissuebill.setIstrans("0");
            omsSaleissuebill.setSrcsys(omsTran.getsrcsys());
            List<OmsSaleissuebillentry> list = new ArrayList<>();
            List<OmsTransferbillentry> omsTransferbillentryList = omsTran.getOmsTransferbillentryList();
            if (omsTransferbillentryList != null) {
                for (OmsTransferbillentry omsTranentry : omsTransferbillentryList) {
                    OmsSaleissuebillentry billentry = new OmsSaleissuebillentry();
                    if(isReturn){
                        billentry.setWarehousenumber(omsTran.getTofacilitycode());
                        billentry.setWarehousename(omsTran.getTofacilityname());
                    }else{
                        if (omsSaleissuebill.getStorageorgnumber().equals(tranOutOrg.getOrgnumber())) {
                            billentry.setWarehousenumber(omsTran.getFacilitycode());
                            billentry.setWarehousename(omsTran.getFacilityname());
                        } else {
                            String transferwhnumber = salOrg.getTransferwhnumber();
                            if (StringUtils.isBlank(transferwhnumber)) {
                                map.put("reason", "销售组织:" + salOrg.getOrgnumber() + "的中转仓为空");
                                return map;
                            }
                            billentry.setWarehousenumber(salOrg.getTransferwhnumber());
                            billentry.setWarehousename(salOrg.getTransferwhname());
                        }
                    }
                    billentry.setMaterialnumber(omsTranentry.getSkucode());
                    billentry.setMaterialname(omsTranentry.getSkuname());
                    billentry.setUnitnumber(omsTranentry.getUnit());
                    billentry.setIspresent(0L);
                    billentry.setBaseunitnumber(omsTranentry.getBaseunit());
                    billentry.setQty(omsTranentry.getShipqty().multiply(qty));
                    billentry.setBaseqty(omsTranentry.getBaseshipqty().multiply(qty));
                    BdMaterial material = new BdMaterial();
                    material.setMaterialnumber(omsTranentry.getSkucode());
                    List<BdMaterial> bdMaterials = materialService.selectBdMaterialList(material);
                    if(StringUtils.isEmpty(bdMaterials)){
                        throw new Exception("-"+omsTranentry.getSkucode()+"该物料不存在");
                    }
                    BigDecimal Taxrate = new BigDecimal(bdMaterials.get(0).getTaxrate().toString());
                    billentry.setTaxrate(Taxrate);//税率
                    StringBuffer stringBuffer = new StringBuffer();
                    OmsSaleissuebillentry salentryObject =
                            getSalentryObject(
                                    salOrg, bdCustomer.getCustomernumber(), omsTran.getTradecreatedat()
                                    , omsTranentry.getSkucode(), stringBuffer,billentry);
                    if(salentryObject==null){
                        throw new Exception(stringBuffer.toString());
                    }
                    list.add(billentry);
                }
                omsSaleissuebill.setOmsSaleissuebillentryList(list);
            }
            map.put("target", omsSaleissuebill);
            return map;
        } catch (Exception e) {
            map.put("reason", "顶级节点不同时，生成销售出库单出现异常" + e.getMessage());
            return map;
        }
    }

    /**
     * 顶级节点不同--采购入
     *
     * @param salOrg           销售组织
     * @param purOrg           采购组织
     * @param omsSaleissuebill 销售出库单
     * @param tranInOrg        调入组织
     * @param omsTran          调拨单
     * @return Map
     */
    private Map FirstOrgTranPur(
            OmsOrgunit salOrg, OmsOrgunit purOrg, OmsSaleissuebill omsSaleissuebill
            , OmsOrgunit tranInOrg, OmsTransferbill omsTran,boolean isReturn) {
        Map map = new HashMap();
        try {
            OmsPurinwarehsbill omsPurinwarehsbill = new OmsPurinwarehsbill();
            omsPurinwarehsbill.setBizdate(omsTran.getReceiptdate());
            omsPurinwarehsbill.setBillnumber(omsTaskUtil.setBillNumber(omsPurinwarehsbill));
            omsPurinwarehsbill.setStorageorgnumber(purOrg.getOrgnumber());
            omsPurinwarehsbill.setStorageorgname(purOrg.getOrgname());
            if(isReturn){
                omsPurinwarehsbill.setBiztypenumber("111");
                omsPurinwarehsbill.setBiztypename("普通采购退货");
                omsPurinwarehsbill.setTransactiontypenumber("005");
                omsPurinwarehsbill.setTransactiontypename("成本入库退货");
            }else{
                omsPurinwarehsbill.setBiztypenumber("110");
                omsPurinwarehsbill.setBiztypename("普通采购");
                omsPurinwarehsbill.setTransactiontypenumber("004");
                omsPurinwarehsbill.setTransactiontypename("成本入库");
            }
            BdSupplier bdSupplier = new BdSupplier();
            //查询上级组织对应的供应商编码
            bdSupplier.setInternalcompanynumber(salOrg.getOrgnumber());
            List<BdSupplier> bdSuppliers = supplierService.selectBdSupplierList(bdSupplier);
            bdSupplier = bdSuppliers.get(0);
            omsPurinwarehsbill.setSuppliernumber(bdSupplier.getSuppliernumber());
            omsPurinwarehsbill.setSuppliername(bdSupplier.getSuppliername());
            omsPurinwarehsbill.setCostcenternumber("1.91");
            omsPurinwarehsbill.setCostcentername("关联单位");
            omsPurinwarehsbill.setAccountcompanynumber(purOrg.getOrgnumber());
            omsPurinwarehsbill.setAccountcompanyname(purOrg.getOrgname());
            omsPurinwarehsbill.setCurrency("CNY");
            omsPurinwarehsbill.setExchangerate(new BigDecimal(1));
            omsPurinwarehsbill.setSrcbilltype("调拨单");
            omsPurinwarehsbill.setSrcbillnumber(omsTran.getCode());
            omsPurinwarehsbill.setCreatetime(new Date());
            omsPurinwarehsbill.setSrcsys(omsTran.getsrcsys());
            List<OmsPurinwarehsbillentry> omsPurinwarehsbillentryList = new ArrayList();
            List<OmsSaleissuebillentry> omsSaleissuebillentryList = omsSaleissuebill.getOmsSaleissuebillentryList();
            for (OmsSaleissuebillentry salentry : omsSaleissuebillentryList) {
                OmsPurinwarehsbillentry billentry = new OmsPurinwarehsbillentry();
                if(isReturn){
                    billentry.setWarehousenumber(omsTran.getFacilitycode());
                    billentry.setWarehousename(omsTran.getFacilityname());
                }else{
                    if (omsPurinwarehsbill.getStorageorgnumber().equals(tranInOrg.getOrgnumber())) {
                        billentry.setWarehousenumber(omsTran.getTofacilitycode());
                        billentry.setWarehousename(omsTran.getTofacilityname());
                    } else {
                        String transferwhnumber = purOrg.getTransferwhnumber();
                        if (StringUtils.isBlank(transferwhnumber)) {
                            map.put("reason", "采购组织:" + purOrg.getOrgnumber() + "的中转仓为空");
                            return map;
                        }
                        billentry.setWarehousenumber(purOrg.getTransferwhnumber());
                        billentry.setWarehousename(purOrg.getTransferwhname());
                    }
                }
                billentry.setMaterialnumber(salentry.getMaterialnumber());
                billentry.setMaterialname(salentry.getMaterialname());
                billentry.setUnitnumber(salentry.getUnitnumber());
                billentry.setIspresent(0L);
                billentry.setBaseunitnumber(salentry.getBaseunitnumber());
                billentry.setQty(salentry.getQty());
                billentry.setBaseqty(salentry.getBaseqty());
                billentry.setPrice(salentry.getPrice());
                billentry.setTaxrate(salentry.getTaxrate());
                billentry.setTaxprice(salentry.getTaxprice());
                billentry.setAmount(salentry.getAmount());
                billentry.setTax(salentry.getTax());
                billentry.setTaxamount(salentry.getTaxamount());
                omsPurinwarehsbillentryList.add(billentry);
            }
            omsPurinwarehsbill.setOmsPurinwarehsbillentryList(omsPurinwarehsbillentryList);
            map.put("target", omsPurinwarehsbill);
            return map;
        } catch (Exception e) {
            map.put("reason", "顶级节点不同时，生成采购入库单出现异常" + e.getMessage());
            return map;
        }
    }

    /**
     * 调出组织至节点退货（总）
     *
     * @param orgNode    根节点
     * @param omsTran    调拨单
     * @param tranInOrg  调入组织
     * @param tranOutOrg 调出组织
     * @return Map
     */
    @Transactional
    public Map tranOutrecurPush(OmsOrgunit orgNode, OmsTransferbill omsTran
            , OmsOrgunit tranInOrg, OmsOrgunit tranOutOrg) {
        HashMap hashMap = new HashMap();
        try {
            String floorLongnumber = tranOutOrg.getLongnumber();
            String[] floorSplit = floorLongnumber.split("!");
            for (int i = floorSplit.length - 1; i > 0; i--) {
                //下游组织
                String s1 = floorSplit[i];
                if (s1.equals(orgNode.getOrgnumber())) {
                    break;
                }
                OmsOrgunit omsOrgunit1 = new OmsOrgunit();
                omsOrgunit1.setOrgnumber(s1);
                List<OmsOrgunit> omsOrgunits1 = orgunitService.selectOmsOrgunitList(omsOrgunit1);
                omsOrgunit1 = omsOrgunits1.get(0);
                //上游组织
                String s2 = floorSplit[i - 1];
                OmsOrgunit omsOrgunit2 = new OmsOrgunit();
                omsOrgunit2.setOrgnumber(s2);
                List<OmsOrgunit> omsOrgunits2 = orgunitService.selectOmsOrgunitList(omsOrgunit2);
                omsOrgunit2 = omsOrgunits2.get(0);
                Map map = tranOutCreatSal(omsOrgunit2, omsTran, omsOrgunit1, tranInOrg, false,new BigDecimal("-1"),false);
                if (map.containsKey("reason")) {
                    throw new Exception(map.get("reason").toString());
                }
                OmsSaleissuebill omsSaleissuebill = (OmsSaleissuebill) map.get("target");
                saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
                Map map1 = tranOutCreatPur(omsOrgunit1, omsTran, omsSaleissuebill, omsOrgunit2, tranOutOrg, false,false);
                if (map1.containsKey("reason")) {
                    throw new Exception(map1.get("reason").toString());
                }
                OmsPurinwarehsbill omsPurinwarehsbill = (OmsPurinwarehsbill) map1.get("target");
                purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
            }
            return hashMap;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            hashMap.put("reason", e.toString());
            return hashMap;
        }
    }

    /**
     * 调出组织至节点--销售出(红字)
     *
     * @param upOrg     上级组织
     * @param omsTran   调拨单
     * @param downOrg   下级组织
     * @param tranInOrg 调入组织
     * @param isSub     是否分子公司
     * @return Map
     */
    private Map tranOutCreatSal(OmsOrgunit upOrg, OmsTransferbill omsTran, OmsOrgunit downOrg
            , OmsOrgunit tranInOrg, boolean isSub,BigDecimal qty,boolean isReturn) {
        Map map = new HashMap();
        try {
            OmsSaleissuebill omsSaleissuebill = new OmsSaleissuebill();
            omsSaleissuebill.setBizdate(omsTran.getReceiptdate());
            omsSaleissuebill.setBillnumber(omsTaskUtil.setBillNumber(omsSaleissuebill));
            omsSaleissuebill.setStorageorgnumber(upOrg.getOrgnumber());
            omsSaleissuebill.setStorageorgname(upOrg.getOrgname());
            if(isReturn){
                omsSaleissuebill.setBiztypenumber("210");
                omsSaleissuebill.setBiztypename("普通销售");
                omsSaleissuebill.setTransactiontypenumber("012");
                omsSaleissuebill.setTransactiontypename("成本出库");
            }else{
                omsSaleissuebill.setBiztypenumber("211");
                omsSaleissuebill.setBiztypename("普通销售退货");
                omsSaleissuebill.setTransactiontypenumber("013");
                omsSaleissuebill.setTransactiontypename("成本出库退货");
            }
            BdCustomer bdCustomer = new BdCustomer();
            bdCustomer.setInternalcompanynumber(downOrg.getOrgnumber());
            List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
            bdCustomer = bdCustomers.get(0);
            omsSaleissuebill.setCustomernumber(bdCustomer.getCustomernumber());
            omsSaleissuebill.setCustomername(bdCustomer.getCustomername());
            omsSaleissuebill.setAccountcompanynumber(upOrg.getOrgnumber());
            omsSaleissuebill.setAccountcompanyname(upOrg.getOrgname());
            omsSaleissuebill.setCostcenternumber("1.91");
            omsSaleissuebill.setCostcentername("关联单位");
            omsSaleissuebill.setCurrency("CNY");
            omsSaleissuebill.setExchangerate(new BigDecimal(1));
            omsSaleissuebill.setSrcbilltype("调拨单");
            omsSaleissuebill.setSrcbillnumber(omsTran.getCode());
            omsSaleissuebill.setCreatetime(new Date());
            omsSaleissuebill.setIsoutcustomer(0L);
            omsSaleissuebill.setIstrans("0");
            omsSaleissuebill.setSrcsys(omsTran.getsrcsys());
            List<OmsSaleissuebillentry> list = new ArrayList<>();
            List<OmsTransferbillentry> omsTransferbillentryList = omsTran.getOmsTransferbillentryList();
            if (omsTransferbillentryList != null) {
                for (OmsTransferbillentry omsTranentry : omsTransferbillentryList) {
                    OmsSaleissuebillentry billentry = new OmsSaleissuebillentry();
                    if(isReturn){
                        billentry.setWarehousenumber(omsTran.getFacilitycode());
                        billentry.setWarehousename(omsTran.getFacilityname());
                    }else{
                        if (omsSaleissuebill.getStorageorgnumber().equals(tranInOrg.getOrgnumber())) {
                            billentry.setWarehousenumber(omsTran.getTofacilitycode());
                            billentry.setWarehousename(omsTran.getTofacilityname());
                        } else {
                            String transferwhnumber = upOrg.getTransferwhnumber();
                            if (StringUtils.isBlank(transferwhnumber)) {
                                map.put("reason", "销售组织:" + upOrg.getOrgnumber() + "的中转仓为空");
                                return map;
                            }
                            billentry.setWarehousenumber(upOrg.getTransferwhnumber());
                            billentry.setWarehousename(upOrg.getTransferwhname());
                        }
                    }
                    billentry.setMaterialnumber(omsTranentry.getSkucode());
                    billentry.setMaterialname(omsTranentry.getSkuname());
                    billentry.setUnitnumber(omsTranentry.getUnit());
                    billentry.setBaseunitnumber(omsTranentry.getBaseunit());
                    billentry.setIspresent(0L);
                    billentry.setQty(omsTranentry.getShipqty().multiply(qty));
                    billentry.setBaseqty(omsTranentry.getBaseshipqty().multiply(qty));
                    BdMaterial material = new BdMaterial();
                    material.setMaterialnumber(omsTranentry.getSkucode());
                    List<BdMaterial> bdMaterials = materialService.selectBdMaterialList(material);
                    if(StringUtils.isEmpty(bdMaterials)){
                        throw new Exception("-"+omsTranentry.getSkucode()+"该物料不存在");
                    }
                    BigDecimal Taxrate = new BigDecimal(bdMaterials.get(0).getTaxrate().toString());
                    billentry.setTaxrate(Taxrate);//税率
                    //计算金额价税相关数据
                    StringBuffer stringBuffer = new StringBuffer();
                    OmsSaleissuebillentry salentryObject =
                            getSalentryObject(upOrg, bdCustomer.getCustomernumber(), omsTran.getTradecreatedat(), omsTranentry.getSkucode(), stringBuffer,billentry);
                    if(salentryObject==null){
                        throw new Exception(stringBuffer.toString());
                    }
                    list.add(billentry);
                }
                omsSaleissuebill.setOmsSaleissuebillentryList(list);
            }
            map.put("target", omsSaleissuebill);
            return map;
        } catch (Exception e) {
            map.put("reason", "调出组织至节点，生成销售出库单出现异常" + e.getMessage());
            if (isSub) {
                map.put("reason", "调出一级组织至实业，生成销售出库单出现异常" + e.getMessage());
            }
            return map;
        }
    }

    /**
     * 调出组织至节点--采购入
     *
     * @param downOrg          下级组织
     * @param omsTran          调拨单
     * @param omsSaleissuebill 销售出库单
     * @param upOrg            上级组织
     * @param tranOutOrg       调出组织
     * @param isSub            是否分子公司
     * @return Map
     */
    private Map tranOutCreatPur(OmsOrgunit downOrg, OmsTransferbill omsTran
            , OmsSaleissuebill omsSaleissuebill, OmsOrgunit upOrg, OmsOrgunit tranOutOrg, boolean isSub,boolean isReturn) {
        Map map = new HashMap();
        try {
            OmsPurinwarehsbill omsPurinwarehsbill = new OmsPurinwarehsbill();
            omsPurinwarehsbill.setBizdate(omsTran.getReceiptdate());
            omsPurinwarehsbill.setBillnumber(omsTaskUtil.setBillNumber(omsPurinwarehsbill));
            omsPurinwarehsbill.setStorageorgnumber(downOrg.getOrgnumber());
            omsPurinwarehsbill.setStorageorgname(downOrg.getOrgname());
            if(isReturn){
                omsPurinwarehsbill.setBiztypenumber("110");
                omsPurinwarehsbill.setBiztypename("普通采购");
                omsPurinwarehsbill.setTransactiontypenumber("004");
                omsPurinwarehsbill.setTransactiontypename("成本入库");
            }else{
                omsPurinwarehsbill.setBiztypenumber("111");
                omsPurinwarehsbill.setBiztypename("普通采购退货");
                omsPurinwarehsbill.setTransactiontypenumber("005");
                omsPurinwarehsbill.setTransactiontypename("成本入库退货");
            }
            BdSupplier bdSupplier = new BdSupplier();
            //查询上级组织对应的供应商编码
            bdSupplier.setInternalcompanynumber(upOrg.getOrgnumber());
            List<BdSupplier> bdSuppliers = supplierService.selectBdSupplierList(bdSupplier);
            bdSupplier = bdSuppliers.get(0);
            omsPurinwarehsbill.setSuppliernumber(bdSupplier.getSuppliernumber());
            omsPurinwarehsbill.setSuppliername(bdSupplier.getSuppliername());
            omsPurinwarehsbill.setCostcenternumber("1.91");
            omsPurinwarehsbill.setCostcentername("关联单位");
            omsPurinwarehsbill.setAccountcompanynumber(downOrg.getOrgnumber());
            omsPurinwarehsbill.setAccountcompanyname(downOrg.getOrgname());
            omsPurinwarehsbill.setCurrency("CNY");
            omsPurinwarehsbill.setExchangerate(new BigDecimal(1));
            omsPurinwarehsbill.setSrcbilltype("调拨单");
            omsPurinwarehsbill.setSrcbillnumber(omsTran.getCode());
            omsPurinwarehsbill.setCreatetime(new Date());
            omsPurinwarehsbill.setSrcsys(omsTran.getsrcsys());
            List<OmsPurinwarehsbillentry> omsPurinwarehsbillentryList = new ArrayList();
            List<OmsSaleissuebillentry> omsSaleissuebillentryList = omsSaleissuebill.getOmsSaleissuebillentryList();
            for (OmsSaleissuebillentry salentry : omsSaleissuebillentryList) {
                OmsPurinwarehsbillentry billentry = new OmsPurinwarehsbillentry();
                if(isReturn){
                    billentry.setWarehousenumber(omsTran.getTofacilitycode());
                    billentry.setWarehousename(omsTran.getTofacilityname());
                }else{
                    if (omsPurinwarehsbill.getStorageorgnumber().equals(tranOutOrg.getOrgnumber())) {
                        billentry.setWarehousenumber(omsTran.getFacilitycode());
                        billentry.setWarehousename(omsTran.getFacilityname());
                    } else {
                        String transferwhnumber = downOrg.getTransferwhnumber();
                        if (StringUtils.isBlank(transferwhnumber)) {
                            map.put("reason", "采购组织:" + downOrg.getOrgnumber() + "的中转仓为空");
                            return map;
                        }
                        billentry.setWarehousenumber(downOrg.getTransferwhnumber());
                        billentry.setWarehousename(downOrg.getTransferwhname());
                    }
                }
                billentry.setMaterialnumber(salentry.getMaterialnumber());
                billentry.setMaterialname(salentry.getMaterialname());
                billentry.setUnitnumber(salentry.getUnitnumber());
                billentry.setBaseunitnumber(salentry.getBaseunitnumber());
                billentry.setIspresent(0L);
                billentry.setQty(salentry.getQty());
                billentry.setBaseqty(salentry.getBaseqty());
                billentry.setPrice(salentry.getPrice());
                billentry.setTaxrate(salentry.getTaxrate());
                billentry.setTaxprice(salentry.getTaxprice());
                billentry.setAmount(salentry.getAmount());
                billentry.setTax(salentry.getTax());
                billentry.setTaxamount(salentry.getTaxamount());
                omsPurinwarehsbillentryList.add(billentry);
            }
            omsPurinwarehsbill.setOmsPurinwarehsbillentryList(omsPurinwarehsbillentryList);
            map.put("target", omsPurinwarehsbill);
            return map;
        } catch (Exception e) {
            map.put("reason", "调出组织至节点，生成采购入库单出现异常" + e.getMessage());
            if (isSub) {
                map.put("reason", "调出一级组织至实业，生成采购入库单出现异常" + e.getMessage());
            }
            return map;
        }
    }

    /**
     * 节点销售至调入组织（总）
     *
     * @param node       根节点
     * @param omsTran    调拨单
     * @param tranInOrg  调入组织
     * @param tranOutOrg 调出组织
     * @return Map
     */
    @Transactional
    public Map tranInrecurPush(OmsOrgunit node, OmsTransferbill omsTran
            , OmsOrgunit tranInOrg, OmsOrgunit tranOutOrg) {
        HashMap hashMap = new HashMap();
        try {
            String floorLongnumber = tranInOrg.getLongnumber();
            String[] floorSplit = floorLongnumber.split("!");
            String nodeLongnumber = node.getLongnumber();
            String[] nodeSplit = nodeLongnumber.split("!");
            for (int i = nodeSplit.length - 1; i < floorSplit.length; i++) {
                //当前组织
                String s1 = floorSplit[i];
                //如果销售组织等于调入组织,跳出循环
                if (!StringUtils.isBlank(s1) && s1.equals(tranInOrg.getOrgnumber())) {
                    break;
                }
                //销售组织
                OmsOrgunit omsOrgunitSal = new OmsOrgunit();
                omsOrgunitSal.setOrgnumber(s1);
                List<OmsOrgunit> omsOrgunits1 = orgunitService.selectOmsOrgunitList(omsOrgunitSal);
                omsOrgunitSal = omsOrgunits1.get(0);
                //采购组织
                String s2 = floorSplit[i + 1];
                OmsOrgunit omsOrgunitPur = new OmsOrgunit();
                omsOrgunitPur.setOrgnumber(s2);
                List<OmsOrgunit> omsOrgunits2 = orgunitService.selectOmsOrgunitList(omsOrgunitPur);
                omsOrgunitPur = omsOrgunits2.get(0);
                Map map = tranInCreatSal(omsOrgunitSal, omsTran, omsOrgunitPur, tranOutOrg, false,new BigDecimal("1"),false);
                if (map.containsKey("reason")) {
                    throw new Exception(map.get("reason").toString());
                }
                OmsSaleissuebill omsSaleissuebill = (OmsSaleissuebill) map.get("target");
                saleissuebillService.insertOmsSaleissuebill(omsSaleissuebill);
                Map map1 = tranInCreatPur(omsOrgunitPur, omsTran, omsSaleissuebill, omsOrgunitSal, tranInOrg, false,false);
                if (map1.containsKey("reason")) {
                    throw new Exception(map1.get("reason").toString());
                }
                OmsPurinwarehsbill omsPurinwarehsbill = (OmsPurinwarehsbill) map1.get("target");
                purinwarehsbillService.insertOmsPurinwarehsbill(omsPurinwarehsbill);
            }
            return hashMap;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            hashMap.put("reason", e.toString());
            return hashMap;
        }
    }

    /**
     * 节点销售至调入组织--销售出
     *
     * @param salOrg     销售组织
     * @param omsTran    调拨单
     * @param purOrg     采购组织
     * @param tranOutOrg 调出组织
     * @param isSub      是否分子公司
     * @return Map
     */
    private Map tranInCreatSal(OmsOrgunit salOrg, OmsTransferbill omsTran, OmsOrgunit purOrg
            , OmsOrgunit tranOutOrg, boolean isSub,BigDecimal qty,boolean isReturn) {
        Map map = new HashMap();
        try {
            OmsSaleissuebill omsSaleissuebill = new OmsSaleissuebill();
            omsSaleissuebill.setBizdate(omsTran.getReceiptdate());
            omsSaleissuebill.setBillnumber(omsTaskUtil.setBillNumber(omsSaleissuebill));
            omsSaleissuebill.setStorageorgnumber(salOrg.getOrgnumber());
            omsSaleissuebill.setStorageorgname(salOrg.getOrgname());
            if(isReturn){
                omsSaleissuebill.setBiztypenumber("211");
                omsSaleissuebill.setBiztypename("普通销售退货");
                omsSaleissuebill.setTransactiontypenumber("013");
                omsSaleissuebill.setTransactiontypename("成本出库退货");
            }else{
                omsSaleissuebill.setBiztypenumber("210");
                omsSaleissuebill.setBiztypename("普通销售");
                omsSaleissuebill.setTransactiontypenumber("012");
                omsSaleissuebill.setTransactiontypename("成本出库");
            }
            BdCustomer bdCustomer = new BdCustomer();
            bdCustomer.setInternalcompanynumber(purOrg.getOrgnumber());
            List<BdCustomer> bdCustomers = customerService.selectBdCustomerList(bdCustomer);
            bdCustomer = bdCustomers.get(0);
            omsSaleissuebill.setCustomernumber(bdCustomer.getCustomernumber());
            omsSaleissuebill.setCustomername(bdCustomer.getCustomername());
            omsSaleissuebill.setAccountcompanynumber(salOrg.getOrgnumber());
            omsSaleissuebill.setAccountcompanyname(salOrg.getOrgname());
            omsSaleissuebill.setCostcenternumber("1.91");
            omsSaleissuebill.setCostcentername("关联单位");
            omsSaleissuebill.setCurrency("CNY");
            omsSaleissuebill.setExchangerate(new BigDecimal(1));
            omsSaleissuebill.setSrcbilltype("调拨单");
            omsSaleissuebill.setSrcbillnumber(omsTran.getCode());
            omsSaleissuebill.setCreatetime(new Date());
            omsSaleissuebill.setIsoutcustomer(0L);
            omsSaleissuebill.setIstrans("0");
            omsSaleissuebill.setSrcsys(omsTran.getsrcsys());
            List<OmsSaleissuebillentry> list = new ArrayList<>();
            List<OmsTransferbillentry> omsTransferbillentryList = omsTran.getOmsTransferbillentryList();
            if (omsTransferbillentryList != null) {
                for (OmsTransferbillentry omsTranentry : omsTransferbillentryList) {
                    OmsSaleissuebillentry billentry = new OmsSaleissuebillentry();
                    if(isReturn){
                        billentry.setWarehousenumber(omsTran.getTofacilitycode());
                        billentry.setWarehousename(omsTran.getTofacilityname());
                    }else{
                        if (omsSaleissuebill.getStorageorgnumber().equals(tranOutOrg.getOrgnumber())) {
                            billentry.setWarehousenumber(omsTran.getFacilitycode());
                            billentry.setWarehousename(omsTran.getFacilityname());
                        } else {
                            String transferwhnumber = salOrg.getTransferwhnumber();
                            if (StringUtils.isBlank(transferwhnumber)) {
                                map.put("reason", "销售组织:" + salOrg.getOrgnumber() + "的中转仓为空");
                                return map;
                            }
                            billentry.setWarehousenumber(salOrg.getTransferwhnumber());
                            billentry.setWarehousename(salOrg.getTransferwhname());
                        }
                    }
                    billentry.setMaterialnumber(omsTranentry.getSkucode());
                    billentry.setMaterialname(omsTranentry.getSkuname());
                    billentry.setUnitnumber(omsTranentry.getUnit());
                    billentry.setIspresent(0L);
                    billentry.setBaseunitnumber(omsTranentry.getBaseunit());
                    billentry.setQty(omsTranentry.getShipqty().multiply(qty));
                    billentry.setBaseqty(omsTranentry.getBaseshipqty().multiply(qty));
                    BdMaterial material = new BdMaterial();
                    material.setMaterialnumber(omsTranentry.getSkucode());
                    List<BdMaterial> bdMaterials = materialService.selectBdMaterialList(material);
                    if(StringUtils.isEmpty(bdMaterials)){
                        throw new Exception("-"+omsTranentry.getSkucode()+"该物料不存在");
                    }
                    BigDecimal Taxrate = new BigDecimal(bdMaterials.get(0).getTaxrate().toString());
                    billentry.setTaxrate(Taxrate);//税率
                    //计算金额价税相关数据
                    StringBuffer stringBuffer = new StringBuffer();
                    OmsSaleissuebillentry salentryObject =
                            getSalentryObject(salOrg, bdCustomer.getCustomernumber(), omsTran.getTradecreatedat(), omsTranentry.getSkucode(), stringBuffer,billentry);
                    if(salentryObject==null){
                        throw new Exception(stringBuffer.toString());
                    }
                    list.add(billentry);
                }
                omsSaleissuebill.setOmsSaleissuebillentryList(list);
            }
            map.put("target", omsSaleissuebill);
            return map;
        } catch (Exception e) {
            map.put("reason", "节点销售至调入组织，生成销售出库单出现异常" + e.getMessage());
            if (isSub) {
                map.put("reason", "实业销售至调入一级组织，生成销售出库单出现异常" + e.getMessage());
            }
            return map;
        }
    }

    /**
     * 节点销售至调入组织--采购入
     *
     * @param purOrg           采购组织
     * @param omsTran          调拨单
     * @param omsSaleissuebill 销售出库单
     * @param salOrg           销售组织
     * @param tranInOrg        调入组织
     * @param isSub            是否分子公司
     * @return Map
     */
    private Map tranInCreatPur(OmsOrgunit purOrg, OmsTransferbill omsTran
            , OmsSaleissuebill omsSaleissuebill, OmsOrgunit salOrg, OmsOrgunit tranInOrg, boolean isSub,boolean isReturn) {
        Map map = new HashMap();
        try {
            OmsPurinwarehsbill omsPurinwarehsbill = new OmsPurinwarehsbill();
            omsPurinwarehsbill.setBizdate(omsTran.getReceiptdate());
            omsPurinwarehsbill.setBillnumber(omsTaskUtil.setBillNumber(omsPurinwarehsbill));
            omsPurinwarehsbill.setStorageorgnumber(purOrg.getOrgnumber());
            omsPurinwarehsbill.setStorageorgname(purOrg.getOrgname());
            if(isReturn){
                omsPurinwarehsbill.setBiztypenumber("111");
                omsPurinwarehsbill.setBiztypename("普通采购退货");
                omsPurinwarehsbill.setTransactiontypenumber("005");
                omsPurinwarehsbill.setTransactiontypename("成本入库退货");
            }else{
                omsPurinwarehsbill.setBiztypenumber("110");
                omsPurinwarehsbill.setBiztypename("普通采购");
                omsPurinwarehsbill.setTransactiontypenumber("004");
                omsPurinwarehsbill.setTransactiontypename("成本入库");
            }
            BdSupplier bdSupplier = new BdSupplier();
            //查询上级组织对应的供应商编码
            bdSupplier.setInternalcompanynumber(salOrg.getOrgnumber());
            List<BdSupplier> bdSuppliers = supplierService.selectBdSupplierList(bdSupplier);
            bdSupplier = bdSuppliers.get(0);
            omsPurinwarehsbill.setSuppliernumber(bdSupplier.getSuppliernumber());
            omsPurinwarehsbill.setSuppliername(bdSupplier.getSuppliername());
            omsPurinwarehsbill.setCostcenternumber("1.91");
            omsPurinwarehsbill.setCostcentername("关联单位");
            omsPurinwarehsbill.setAccountcompanynumber(purOrg.getOrgnumber());
            omsPurinwarehsbill.setAccountcompanyname(purOrg.getOrgname());
            omsPurinwarehsbill.setCurrency("CNY");
            omsPurinwarehsbill.setExchangerate(new BigDecimal(1));
            omsPurinwarehsbill.setSrcbilltype("调拨单");
            omsPurinwarehsbill.setSrcbillnumber(omsTran.getCode());
            omsPurinwarehsbill.setCreatetime(new Date());
            omsPurinwarehsbill.setSrcsys(omsTran.getsrcsys());
            List<OmsPurinwarehsbillentry> omsPurinwarehsbillentryList = new ArrayList();
            List<OmsSaleissuebillentry> omsSaleissuebillentryList = omsSaleissuebill.getOmsSaleissuebillentryList();
            for (OmsSaleissuebillentry salentry : omsSaleissuebillentryList) {
                OmsPurinwarehsbillentry billentry = new OmsPurinwarehsbillentry();
                if(isReturn){
                    billentry.setWarehousenumber(omsTran.getFacilitycode());
                    billentry.setWarehousename(omsTran.getFacilityname());
                }else{
                    if (omsPurinwarehsbill.getStorageorgnumber().equals(tranInOrg.getOrgnumber())) {
                        billentry.setWarehousenumber(omsTran.getTofacilitycode());
                        billentry.setWarehousename(omsTran.getTofacilityname());
                    } else {
                        String transferwhnumber = purOrg.getTransferwhnumber();
                        if (StringUtils.isBlank(transferwhnumber)) {
                            map.put("reason", "采购组织:" + purOrg.getOrgnumber() + "的中转仓为空");
                            return map;
                        }
                        billentry.setWarehousenumber(purOrg.getTransferwhnumber());
                        billentry.setWarehousename(purOrg.getTransferwhname());
                    }
                }
                billentry.setMaterialnumber(salentry.getMaterialnumber());
                billentry.setMaterialname(salentry.getMaterialname());
                billentry.setUnitnumber(salentry.getUnitnumber());
                billentry.setIspresent(0L);
                billentry.setBaseunitnumber(salentry.getBaseunitnumber());
                billentry.setQty(salentry.getQty());
                billentry.setBaseqty(salentry.getBaseqty());
                billentry.setPrice(salentry.getPrice());
                billentry.setTaxrate(salentry.getTaxrate());
                billentry.setTaxprice(salentry.getTaxprice());
                billentry.setAmount(salentry.getAmount());
                billentry.setTax(salentry.getTax());
                billentry.setTaxamount(salentry.getTaxamount());
                omsPurinwarehsbillentryList.add(billentry);
            }
            omsPurinwarehsbill.setOmsPurinwarehsbillentryList(omsPurinwarehsbillentryList);
            map.put("target", omsPurinwarehsbill);
            return map;
        } catch (Exception e) {
            map.put("reason", "节点销售至调入组织，生成采购入库单出现异常" + e.getMessage());
            if (isSub) {
                map.put("reason", "实业销售至调入一级组织，生成采购入库单出现异常" + e.getMessage());
            }
            return map;
        }
    }

    /**
     * 计算销售出库分录对象
     * @param saleOrg 销售组织
     * @param customerNumber 客户编码
     * @param bizdate 业务日期
     * @param materialNumber 物料编码
     * @param stringBuffer StringBuffer
     * @param omsSaleissuebillentry 销售分录对象
     * @return
     */
    public OmsSaleissuebillentry getSalentryObject(OmsOrgunit saleOrg,String customerNumber, Date bizdate, String materialNumber, StringBuffer stringBuffer,OmsSaleissuebillentry omsSaleissuebillentry){
        BigDecimal taxPrice = omsTaskUtil.getTaxPrice(saleOrg, customerNumber, bizdate, materialNumber, stringBuffer);
        if (StringUtils.isNull(taxPrice)) {
            return null;
        }
        //含税单价
        omsSaleissuebillentry.setTaxprice(taxPrice);
        BigDecimal tempTaxrate = omsSaleissuebillentry.getTaxrate();
        omsSaleissuebillentry.setTaxrate(tempTaxrate);
        BigDecimal taxrate = tempTaxrate;
        if (StringUtils.isNull(tempTaxrate)) {
            taxrate = BigDecimal.ZERO;
        }
        //税率
        BigDecimal tempTaxRate = OmsTaskUtil.formatTaxRate(taxrate);
        //单价
        BigDecimal price = taxPrice.divide(tempTaxRate.add(BigDecimal.valueOf(1)),6,BigDecimal.ROUND_HALF_UP);
        omsSaleissuebillentry.setPrice(price);
        //税价合计
        BigDecimal taxAmount = taxPrice.multiply(omsSaleissuebillentry.getQty()).setScale(6, RoundingMode.HALF_UP);
        omsSaleissuebillentry.setTaxamount(taxAmount);
        //金额
//        BigDecimal amount = taxAmount.divide(tempTaxRate.add(BigDecimal.valueOf(1)),2,BigDecimal.ROUND_HALF_UP);

        BigDecimal amount = price.multiply(omsSaleissuebillentry.getQty()).setScale(2, RoundingMode.HALF_UP);
        omsSaleissuebillentry.setAmount(amount);
        //税额
        BigDecimal tax = taxAmount.subtract(amount);
        omsSaleissuebillentry.setTax(tax);
        return omsSaleissuebillentry;
    }

}
